package com.chendx.store.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.customer.pojo.Customer;
import com.chendx.model.user.pojo.User;
import com.chendx.store.user.service.NoticeService;
import com.chendx.store.utils.AppThreadLocalUtils;
import com.chendx.store.utils.CustomerThreadLocalUtils;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by chendx on 2022/4/28.
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult send(Map params,String customer) {

        String username = username();
        if (StringUtils.isEmpty(username)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //内容处理
        String content = (String) params.get("value");
        String type = (String) params.get("type");
        Map<String,Object> map = new HashMap<>();
        Date date = new Date();
        map.put("type",type);
        map.put("content",content);
        map.put("username",username);
        map.put("date",date);
        //用户的聊天记录
        String redisKey = "chat:"+username+":"+username+"_with_"+customer;
        redisTemplate.boundZSetOps(redisKey).add(JSON.toJSONString(map),date.getTime());
        //mq队列处理
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        Queue toQueue = new Queue(username+"_queue_" + customer);
        rabbitAdmin.declareQueue(toQueue);
        DirectExchange exchange = new DirectExchange("customer_queue_exchange");
        Binding binding = BindingBuilder.bind(toQueue).to(exchange).with(username + "_queue_" + customer);
        rabbitAdmin.declareBinding(binding);


        //对方的聊天记录
        String redisKey2 = "chat:"+customer+":"+customer+"_with_"+username;
        redisTemplate.boundZSetOps(redisKey2).add(JSON.toJSONString(map),date.getTime());

        Map<String,String> param = new HashMap<>();
        param.put("username",username);
        param.put("customer",customer);

        rabbitTemplate.convertAndSend("customer_queue_exchange",username+"_queue_" + customer, JSON.toJSONString(param));
    //  rabbitTemplate.convertAndSend("customer_queue_exchange",customer+"_queue_" + user.getUsername(), JSON.toJSONString(param));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    @Override
    public ResponseResult getNotice(String customer) {
        String username = username();
        if (StringUtils.isEmpty(username)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String redisKey = "chat:"+username+":"+username+"_with_"+customer;
        Set<String> strings = redisTemplate.boundZSetOps(redisKey).range(0, -1);
        List<Map > list = new ArrayList<>();
        for (String str : strings){
            Map map = JSON.parseObject(str, Map.class);
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult getNoticeCount(String customer) {
        String username = username();
        if (StringUtils.isEmpty(username)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String key = "chat:"+username +"_no_read_notice_count_for_" + customer;
        Object o = redisTemplate.boundHashOps(key).get(customer);
        Integer count = 0;
        if (o != null){
            count = Integer.valueOf(String.valueOf(o));
        }
        return ResponseResult.okResult(count);
    }

    @Override
    public ResponseResult readNotice(String customer) {
        String username = username();
        if (StringUtils.isEmpty(username)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String cusKey = "chat:"+username +"_no_read_notice_count_for_" + customer;
        redisTemplate.boundHashOps(cusKey).delete(customer);
      /*  User user = AppThreadLocalUtils.get();
        Customer cus = CustomerThreadLocalUtils.get();
        if (cus != null && cus.getUsername() != null){
            String cusKey = "chat:"+cus.getUsername() +"_no_read_notice_count_for_" + customer;
            redisTemplate.boundHashOps(cusKey).delete(customer);
        }else if (user != null && user.getUsername() != null){
            String username = user.getUsername();
            String key = "chat:"+username +"_no_read_notice_count_for_" + customer;
            redisTemplate.boundHashOps(key).delete(customer);
        }else{
            if (user == null || user.getId() == null || user.getUsername() == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
            if (cus == null || cus.getId() == null || cus.getUsername() == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
            }
        }*/
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private String username(){
        String username = null;
        User user = AppThreadLocalUtils.get();
        System.out.println("user "+ JSON.toJSONString(user));
        if (user == null || user.getUsername() == null || user.getId() == null){
            System.out.println("user == null || user.getUsername() == null || user.getId() == null");
            Customer cus = CustomerThreadLocalUtils.get();
            System.out.println("user "+ JSON.toJSONString(cus));
            if (cus != null && !StringUtils.isEmpty(cus.getUsername()) && !StringUtils.isEmpty(cus.getId())){
                System.out.println("cus != null && !StringUtils.isEmpty(cus.getUsername()) && !StringUtils.isEmpty(cus.getId())");
                username = cus.getUsername();
            }
        }else {
            username = user.getUsername();
        }
        return username;
    }
}
